# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 13:19:20 2017

@author: hfutzf
"""
from PIL import Image
import itchat
import win32com.client 
import cv2,os
import win32api,time
from arduino import Arduino 
from PIL import ImageGrab
import wave
from pyaudio import PyAudio,paInt16
import face_recognition



framerate=8000
NUM_SAMPLES=2000
channels=1
sampwidth=2
TIME=2
voice= win32com.client.Dispatch("SAPI.SpVoice")
itchat.auto_login(True)

face_cascade = cv2.CascadeClassifier(r'./haarcascade_frontalface_default.xml')
try:
    b = Arduino('COM8')
    pin = 8

    b.output([pin]) 
except:
    pass

itchat.send('python——微信宿舍监控系统\n1.输入照片:发送宿舍实时图像信息。\n2.输入视频:发送宿\
舍实时视频监控信息\n3.发送#+文件（或者程序），远程打开文件\n【4.输入开灯，则arduino上的13号led\
灯点亮\n5.输入关灯，则arduino上的13号led灯熄灭】\
\n6.发送除上述情况以外的文本，远程实时文本转语音\
输出\n7.输入开始监控+监控时间，电脑开启摄像头开始监控，若识别出人脸，则通过微信向您报警，并保留图片和视频\
\n8.输入结束监控，则结束监控\n9.输入录音+时间：则发送规定时间的录音\n10.输入锁屏，则电\
脑会锁屏\n11.输入关机+等待时间，则会在等待时间后关机\n12.输入截屏，会发送电脑截\
屏\n13.发送*+文件（或者程序），远程发送文件\n14.输入&+xxpath+朋友，使朋友接受xx图\
片\n15.输入cmd-+系统行命令，执行cmd命令',toUserName='filehelper')


care_people=str('杜永峰')
users = itchat.search_friends(name=care_people)
userName = users[0]['UserName']
                
def detect(photo):
    img = face_recognition.load_image_file(photo)
    face_locations = face_recognition.face_locations(img)
    return face_locations


def save_wave_file(filename,data):
    '''save the date to the wavfile'''
    wf=wave.open(filename,'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(sampwidth)
    wf.setframerate(framerate)
    wf.writeframes(b"".join(data))
    wf.close()

def my_record(t):
    pa=PyAudio()
    stream=pa.open(format = paInt16,channels=1,
                   rate=framerate,input=True,
                   frames_per_buffer=NUM_SAMPLES)
    my_buf=[]
    count=0
    while count<TIME*int(t):#控制录音时间
        string_audio_data = stream.read(NUM_SAMPLES)
        my_buf.append(string_audio_data)
        count+=1
    save_wave_file('01.wav',my_buf)
    stream.close()

def video():
            cap = cv2.VideoCapture(0)
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            out = cv2.VideoWriter('output.avi',fourcc, 5.0, (640,480))
            
            start_time=time.clock()
            while(cap.isOpened() and (time.clock()-start_time)<3):
                ret, frame = cap.read()
                if ret==True:
                    frame = cv2.flip(frame,0)
                    out.write(frame)
                    
                    # 释放内存
            cap.release()
            out.release()
def makepic():
            vc = cv2.VideoCapture('output.avi') #读入视频文件  
            c=1  
  
            if vc.isOpened(): #判断是否正常打开  
                rval , frame = vc.read()  
            else:  
                rval = False  
  
            timeF = 4  #视频帧计数间隔频率  
  
            while rval:   #循环读取视频帧  
                rval, frame = vc.read()  
                if(c%timeF == 0): #每隔timeF帧进行存储操作  
                      cv2.imwrite('image'+str(4) + '.jpg',frame) #存储为图像  
                c = c + 1  
                cv2.waitKey(1)  
            vc.release()  
@itchat.msg_register('Text') #注册文本消息
def text_reply(msg):
    global flag
    message =  msg['Text'] 
    toName = msg['ToUserName'] 
    insert=['照片','视频','开灯','关灯','#','开始监控','结束监控','录音','&','关机','锁屏','截屏','朋友']
    if toName == "filehelper":
        if message == "照片": #远程拍照并发送到手机
            try:
                video()
                makepic()
                im1 = Image.open("image4.jpg")
                im2 = im1.rotate(180)
                im2.save('image.jpg')
                itchat.send('@img@%s'%u'image.jpg',toUserName='filehelper')
            except:
                itchat.send('照片发送失败',toUserName='filehelper')
        if not((message[:2] in insert) or (message[:4] in insert)or message[0]=='#' or  message[0]=='*' or message[0]=='&' or message[:3]=='cmd'):
            voice.Speak(message)
            itchat.send('[文本已成功转为语音读出]',toUserName='filehelper')
        if message[0]=='#':
            if os.path.exists(message[1:]):
                try:
                    win32api.ShellExecute(0,'open', message[1:], '','',1)
                    time.sleep(3)
                    im = ImageGrab.grab()
                    im.save('cut.jpg')
                    itchat.send(message[1:]+'已经成功打开',toUserName='filehelper')
                    itchat.send('屏幕截图如下所示',toUserName='filehelper')
                    itchat.send('@img@%s'%u'cut.jpg',toUserName='filehelper')
                except:
                    pass
            else:
                itchat.send('打开文件失败',toUserName='filehelper')
        
        if message[0]=='*':
            if os.path.exists(message[1:]):
                try:

                    itchat.send_file(message[1:],toUserName='filehelper')
                    itchat.send('发送成功',toUserName='filehelper')
                except:
                    itchat.send('发送文件失败',toUserName='filehelper')
            else:
                itchat.send('文件不存在',toUserName='filehelper')
        if message[:2]=='录音':
            try:
                my_record(message[2:])
                itchat.send_file('01.wav',toUserName='filehelper')
            except:
                itchat.send('录音失败',toUserName='filehelper')
        if message[0] == "&" and message[-2:]=='朋友':
            try:
                img='F:\\img\\'+str(message[2:-2])+'.jpg'
                itchat.send('@img@%s'%img,toUserName='filehelper')
                itchat.send('@img@%s'%img,toUserName=userName)
                itchat.send('发送成功',toUserName='filehelper')
            except:
               pass
        if message[0] == "&": 
            try:
                img='F:\\img\\'+str(message[1:])+'.jpg'
                itchat.send('@img@%s'%img,toUserName='filehelper')
                
            except:
                itchat.send('发送失败',toUserName='filehelper')
        if message[:3]=='cmd':
            try:
                os.system(str(message[4:]))
                itchat.send('执行成功',toUserName='filehelper')
            except:
                itchat.send('执行失败',toUserName='filehelper')
        if message=='截屏':
            try:
                    im = ImageGrab.grab()
                    im.save('cut.jpg')
                    itchat.send('@img@%s'%u'cut.jpg',toUserName='filehelper')
            except:
                itchat.send('发送失败',toUserName='filehelper')
        if message[:2] == "关机":
            try:
                os.system('shutdown -s -t '+str(message[2:]))
                voice.Speak('您的电脑还有'+message[2:]+'秒关机')
                itchat.send('关机设置成功',toUserName='filehelper')
            except:
                itchat.send('关机设置失败',toUserName='filehelper')
                pass
        if message == "锁屏":
            try:
                os.system('rundll32.exe user32.dll,LockWorkStation')
                itchat.send('锁屏成功',toUserName='filehelper')
            except:
                itchat.send('锁屏失败',toUserName='filehelper')
                pass
            
        if message == "视频":
          try:
            video()
            itchat.send('@vid@%s'%u'output.avi',toUserName='filehelper') 
          except:
              itchat.send('获取视频失败',toUserName='filehelper') 
             
        if message == "关灯":
            try:
                b.setHigh(pin)
                itchat.send('关灯成功！(:',toUserName='filehelper')
            except:
                itchat.send('关灯失败):',toUserName='filehelper') 
        if message == "开灯":
            try:
                b.setLow(pin)
                itchat.send('开灯成功 ):',toUserName='filehelper')
            except:
                itchat.send('开灯失败 ):',toUserName='filehelper')
        if message[:4] == "开始监控":
          global number
          number=0
          t=time.clock()
          while number<1 and int(time.clock()-t)<=int(message[4:]):
            video()
            makepic()
            if number<1 and int(time.clock()-t)%300<=5 and t>10:
                itchat.send('@img@%s'%u'image4.jpg',toUserName='filehelper')
            try:
                im1 = Image.open("image4.jpg")
                im2 = im1.rotate(180)
                im2.save('image4.jpg')
                
                result=detect('image4.jpg')
                    
                if result:
                    number+=1
                    itchat.send('有人在你的书桌附近活动',toUserName='filehelper')
                    itchat.send('@vid@%s'%u'output.mp4',toUserName='filehelper') 
                    itchat.send('@img@%s'%u'image4.jpg',toUserName='filehelper')
                    
                    #voice.Speak('您已经进入视频监控区！')
            except:
                pass
    else:
        return 'I received: %s' % msg['Content']

        
itchat.run()


